<template>
  <view class="verification-page">
    <view class="verification-container">
      <!-- 认证状态展示 -->
      <view class="status-card">
        <view class="status-icon">
          <u-icon 
            :name="verificationStatus.icon" 
            :color="verificationStatus.color" 
            size="60"
          />
        </view>
        <view class="status-info">
          <text class="status-title">{{ verificationStatus.title }}</text>
          <text class="status-desc">{{ verificationStatus.desc }}</text>
        </view>
      </view>

      <!-- 认证表单 -->
      <view v-if="!isVerified" class="verification-form">
        <view class="form-section">
          <view class="section-title">身份信息</view>
          
          <view class="form-item">
            <text class="label">真实姓名</text>
            <input 
              v-model="formData.realName"
              class="input"
              placeholder="请输入真实姓名"
              maxlength="20"
            />
          </view>
          
          <view class="form-item">
            <text class="label">身份证号</text>
            <input 
              v-model="formData.idCard"
              class="input"
              placeholder="请输入身份证号码"
              maxlength="18"
            />
          </view>
        </view>

        <view class="form-section">
          <view class="section-title">身份证照片</view>
          <view class="id-photos">
            <!-- 身份证正面 -->
            <view class="photo-item">
              <text class="photo-label">身份证正面</text>
              <view class="photo-upload" @click="uploadPhoto('front')">
                <image 
                  v-if="formData.idCardFront" 
                  :src="formData.idCardFront" 
                  class="uploaded-photo"
                  mode="aspectFill"
                />
                <view v-else class="upload-placeholder">
                  <u-icon name="camera" size="30" color="#999" />
                  <text class="upload-text">上传正面照片</text>
                </view>
              </view>
            </view>
            
            <!-- 身份证反面 -->
            <view class="photo-item">
              <text class="photo-label">身份证反面</text>
              <view class="photo-upload" @click="uploadPhoto('back')">
                <image 
                  v-if="formData.idCardBack" 
                  :src="formData.idCardBack" 
                  class="uploaded-photo"
                  mode="aspectFill"
                />
                <view v-else class="upload-placeholder">
                  <u-icon name="camera" size="30" color="#999" />
                  <text class="upload-text">上传反面照片</text>
                </view>
              </view>
            </view>
          </view>
          
          <view class="photo-tips">
            <text class="tip-title">拍照要求：</text>
            <text class="tip-item">• 证件信息清晰可见，无遮挡</text>
            <text class="tip-item">• 照片光线充足，无反光</text>
            <text class="tip-item">• 证件在有效期内</text>
          </view>
        </view>

        <view class="submit-section">
          <u-button 
            type="primary" 
            size="large"
            :loading="submitting"
            @click="submitVerification"
            :disabled="!canSubmit"
          >
            提交认证
          </u-button>
        </view>
      </view>

      <!-- 已认证状态 -->
      <view v-else class="verified-info">
        <view class="info-item">
          <text class="info-label">真实姓名</text>
          <text class="info-value">{{ userInfo.realName || '张**' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">身份证号</text>
          <text class="info-value">{{ formatIdCard(userInfo.idCard) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">认证时间</text>
          <text class="info-value">{{ formatDate(userInfo.verifiedAt) }}</text>
        </view>
      </view>
    </view>

    <!-- 提交成功弹窗 -->
    <u-popup v-model="showSuccessModal" mode="center" border-radius="20">
      <view class="success-modal">
        <view class="success-icon">
          <u-icon name="checkmark-circle-fill" size="60" color="#52c41a" />
        </view>
        <view class="success-title">认证信息已提交</view>
        <view class="success-content">
          我们将在1-3个工作日内完成审核，请耐心等待。
        </view>
        <u-button type="primary" @click="goBack" size="large">
          知道了
        </u-button>
      </view>
    </u-popup>
  </view>
</template>

<script>
import apiService from '@/api'
import { API_CONFIG } from '@/api/config'

export default {
  data() {
    return {
      userInfo: {},
      formData: {
        realName: '',
        idCard: '',
        idCardFront: '',
        idCardBack: ''
      },
      submitting: false,
      showSuccessModal: false
    }
  },
  
  computed: {
    isVerified() {
      return this.userInfo.verified || false
    },
    
    verificationStatus() {
      if (this.isVerified) {
        return {
          icon: 'checkmark-circle-fill',
          color: '#52c41a',
          title: '实名认证已通过',
          desc: '您的身份信息已通过验证'
        }
      } else if (this.userInfo.verificationStatus === 'PENDING') {
        return {
          icon: 'clock',
          color: '#faad14',
          title: '认证审核中',
          desc: '我们正在审核您的认证信息，请耐心等待'
        }
      } else if (this.userInfo.verificationStatus === 'REJECTED') {
        return {
          icon: 'close-circle',
          color: '#f5222d',
          title: '认证审核未通过',
          desc: '请重新提交正确的认证信息'
        }
      } else {
        return {
          icon: 'info-circle',
          color: '#1890ff',
          title: '完善身份认证',
          desc: '为了您的账户安全，请完成实名认证'
        }
      }
    },
    
    canSubmit() {
      return this.formData.realName.trim() && 
             this.formData.idCard.trim() && 
             this.formData.idCardFront && 
             this.formData.idCardBack
    }
  },
  
  onLoad() {
    uni.setNavigationBarTitle({
      title: '实名认证'
    })
    this.loadUserInfo()
  },
  
  methods: {
    async loadUserInfo() {
      try {
        const response = await apiService.user.getUserProfile()
        this.userInfo = response.data || response
      } catch (error) {
        console.error('加载用户信息失败:', error)
      }
    },
    
    async uploadPhoto(type) {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })
        
        const tempFilePath = res.tempFilePaths[0]
        
        // 上传图片到服务器
        uni.showLoading({ title: '上传中...' })
        
        const uploadResult = await uni.uploadFile({
          url: `${API_CONFIG.BASE_URL}/files/upload-user`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          }
        })
        
        const uploadData = JSON.parse(uploadResult.data)
        console.log('🔍 上传结果:', uploadData)
        if (uploadData.code === 200) {
          const imageUrl = uploadData.data.url
          console.log(`📸 ${type === 'front' ? '正面' : '反面'}图片URL:`, imageUrl)
          if (type === 'front') {
            this.formData.idCardFront = imageUrl
            console.log('✅ 设置正面图片:', this.formData.idCardFront)
          } else {
            this.formData.idCardBack = imageUrl
            console.log('✅ 设置反面图片:', this.formData.idCardBack)
          }
          // 强制更新视图
          this.$forceUpdate()
          console.log('🔄 当前formData状态:', JSON.stringify(this.formData, null, 2))
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          })
        } else {
          throw new Error(uploadData.message || '上传失败')
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    async submitVerification() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善认证信息',
          icon: 'none'
        })
        return
      }
      
      try {
        this.submitting = true
        
        // 调用实名认证API
        const verificationData = {
          realName: this.formData.realName,
          idCard: this.formData.idCard,
          idCardFront: this.formData.idCardFront,
          idCardBack: this.formData.idCardBack
        }
        
        const result = await apiService.user.submitVerification(verificationData)
        
        if (result.code === 200) {
          uni.showToast({
            title: '提交成功，等待审核',
            icon: 'success'
          })
          this.showSuccessModal = true
          
          // 更新本地用户信息
          const user = uni.getStorageSync('user_info')
          if (user) {
            user.verificationStatus = 'pending'
            uni.setStorageSync('user_info', user)
          }
        } else {
          throw new Error(result.message || '提交失败')
        }
        
      } catch (error) {
        console.error('提交认证失败:', error)
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },
    
    formatIdCard(idCard) {
      if (!idCard) return '******************'
      return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '-'
      return new Date(dateStr).toLocaleDateString()
    },
    
    goBack() {
      this.showSuccessModal = false
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.verification-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.verification-container {
  padding: 32rpx;
}

.status-card {
  background: white;
  border-radius: 16rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  margin-bottom: 32rpx;
}

.status-icon {
  margin-bottom: 24rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.status-title {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 12rpx;
}

.status-desc {
  display: block;
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.verification-form {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 32rpx;
}

.form-section {
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.form-item {
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fafafa;
}

.id-photos {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.photo-item {
  flex: 1;
}

.photo-label {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
  text-align: center;
}

.photo-upload {
  width: 100%;
  height: 240rpx;
  border: 1rpx dashed #d9d9d9;
  border-radius: 8rpx;
  position: relative;
  overflow: hidden;
}

.uploaded-photo {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 12rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.photo-tips {
  background: #f0f7ff;
  padding: 20rpx;
  border-radius: 8rpx;
}

.tip-title {
  display: block;
  font-size: 26rpx;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 12rpx;
}

.tip-item {
  display: block;
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.submit-section {
  margin-bottom: 32rpx;
}

.verified-info {
  background: white;
  border-radius: 16rpx;
  padding: 32rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.success-modal {
  width: 560rpx;
  padding: 60rpx 40rpx;
  text-align: center;
}

.success-icon {
  margin-bottom: 32rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
}

.success-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 40rpx;
}
</style>